<template>
  <el-dialog :close-on-click-modal="false" :draggable=true :model-value="dialogVisible" title="常用脚本"
             width="80%"
             height="80vh"
             :body-style="{ height: '100%', padding: '0', overflow: 'hidden', display: 'flex', flexDirection: 'column' }"
             @close="close">
    <div class="command-dialog-content">
      <!-- 上方操作区域 -->
      <div class="search-container"
           style="padding: 20px; border-radius: 16px; background-color: #f5f7fa; box-shadow: 0 4px 12px rgba(0,0,0,0.04);">
        <div style="display: flex; align-items: center; gap: 20px;">
          <el-input v-model="newCommand.command" placeholder="命令关键词" style="width: 220px;"/>
          <el-input v-model="newCommand.description" placeholder="描述关键词" style="width: 220px;"/>
          <el-tree-select
              v-model="selectedCategoryId"
              :data="treeCategories"
              :props="{ label: 'name', value: 'id', children: 'children' }"
              placeholder="选择分类"
              check-strictly=true
              style="width: 200px"
          />
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="queryCommand">查询</el-button>
        </div>
      </div>

      <!-- 命令列表 -->
      <div class="command-list-container"
           style="padding: 20px; border-radius: 16px; background-color: #f5f7fa; box-shadow: 0 4px 12px rgba(0,0,0,0.04); max-height: calc(80vh - 200px); overflow-y: auto;">
        <el-table :data="commonCommands" border style="width: 100%;">
          <el-table-column label="命令内容" prop="command">
            <template #default="{ row }">
              <span>{{ row.command }}</span>
            </template>
          </el-table-column>
          <el-table-column label="命令描述" prop="description">
            <template #default="{ row }">
              <span>{{ row.description }}</span>
            </template>
          </el-table-column>
          <el-table-column label="分类" prop="categoryName">
            <template #default="{ row }">
              <span>{{ row.categoryName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="创建时间" prop="createTime">
            <template #default="{ row }">
              <span>{{ row.createTime }}</span>
            </template>
          </el-table-column>
          <el-table-column label="更新时间" prop="updateTime">
            <template #default="{ row }">
              <span>{{ row.updateTime }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="220">
            <template #default="scope">
              <el-button size="small" type="success" @click="executeCommand(scope.row.command, true)">执行</el-button>
              <el-button size="small" @click="executeCommand(scope.row.command, false)">填充</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import {ref, computed, onMounted} from 'vue'
import {defineProps, defineEmits} from 'vue'
import {
  getAllCommandCategoryList,
  getAllCommandList,
  queryCommandList,
} from "@/api/webShell/commonScripts";
import {message} from "@/utils/ElmessasgeUtils";
import {ElTreeSelect} from "element-plus";

const emit = defineEmits(['update:dialogVisible', "close", 'execute'])

interface Props {
  dialogVisible: boolean;
}

const props = defineProps<Props>();

// 从后端获取分类数据
const categoriesFromBackend = ref([])
// 常用命令列表
const commonCommands = ref([])
// 当前选中分类
const selectedCategoryId = ref('0')


// 初始化时加载常用命令和分类
onMounted(() => {
  loadCommonCommands();
  updateCategoryList();
})

// 加载常用命令
function loadCommonCommands() {
  getAllCommandList().then((res: any) => {
    if (res.data.code === 200) {
      commonCommands.value = res.data.data;
    } else {
      message("获取常用命令失败", 'error')
    }
  })
}

// 更新分类列表
function updateCategoryList() {
  getAllCommandCategoryList().then((res: any) => {
    if (res.data.code === 200) {
      categoriesFromBackend.value = res.data.data.filter((item: any) => item.id !== '0');
    } else {
      message('获取命令类别失败', 'error')
    }
  })
}

// 查询命令
function queryCommand() {
  queryCommandList({
    command: newCommand.value.command,
    description: newCommand.value.description,
    category: selectedCategoryId.value
  }).then((res: any) => {
    if (res.data.code === 200) {
      commonCommands.value = res.data.data;
    } else {
      message('查询命令失败', 'error')
    }
  })
}

// 重置搜索
function resetSearch() {
  newCommand.value = {command: '', description: ''};
  selectedCategoryId.value = '0';
  loadCommonCommands();
}


// 执行命令
function executeCommand(command: string, execFlag: boolean) {
  emit('execute', command, execFlag)
  close()
}

// 关闭对话框
function close() {
  emit('update:dialogVisible', false)
  emit('close')
}


// 树形分类数据
const treeCategories = computed(() => {
  const categories = [...categoriesFromBackend.value];
  const map = new Map();
  const roots: any[] = [];

  // 添加"全部"分类作为根节点
  roots.push({
    id: '0',
    name: '全部',
    children: [],
    isAll: true
  });

  // 构建树形结构
  categories.forEach((category: any) => {
    map.set(category.id, {...category, children: []});
  });

  categories.forEach(category => {
    const parent = map.get(category.pid);
    if (parent) {
      parent.children.push(map.get(category.id));
    } else if (category.pid === '0') {
      roots[0].children.push(map.get(category.id));
    }
  });

  return roots;
})

// 新命令对象
const newCommand = ref({
  command: '',
  description: ''
})

</script>

<style scoped>
.el-table {
  margin-top: 20px;
  width: 100%;
}

::v-deep .el-tree-node__content {
  padding: 8px !important;
  height: auto !important;
  white-space: normal !important;
  line-height: 1.5;
}

::v-deep .el-tree-node {
  padding-left: 8px;
}

::v-deep .el-tree-node__children {
  padding-left: 16px;
}

::v-deep .el-tree-node__content:hover {
  background-color: #f5f7fa;
}

/* 搜索区域样式 */
.command-dialog-content {
  padding: 20px;
  flex: 1; /* 占据全部可用空间 */
  display: flex;
  flex-direction: column;
  gap: 20px;
  overflow: hidden;
  box-sizing: border-box; /* 确保padding包含在高度内 */
}

.search-container {
  flex: 0 0 auto; /* 不伸缩 */
}

.command-list-container {
  flex: 1 1 auto; /* 占据剩余空间 */
  overflow-y: auto; /* 内容溢出时显示滚动条 */
  min-height: 0; /* 允许flex容器收缩到小于内容高度 */
}

/* 表格样式 */
::v-deep .el-table th {
  background-color: #f5f7fa;
  font-weight: 500;
}

::v-deep .el-table tr:hover > td {
  background-color: #f9fafc;
}

/* 按钮样式 */
::v-deep .el-button--primary {
  background-color: #626AEF;
  border-color: #626AEF;
}

::v-deep .el-button--primary:hover {
  background-color: #5258d7;
  border-color: #5258d7;
}
</style>